#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WMS系统完整重新打包脚本
包含三类应用的完整打包流程
"""

import os
import sys
import subprocess
import shutil
import json
from pathlib import Path
from datetime import datetime

def print_header(title):
    """打印标题"""
    print("\n" + "="*60)
    print(f"  {title}")
    print("="*60)

def print_step(step, description):
    """打印步骤"""
    print(f"\n{step}. {description}")
    print("-" * 40)

def run_command(cmd, description, check=True):
    """运行命令"""
    print(f"执行: {cmd}")
    try:
        result = subprocess.run(cmd, shell=True, check=check, 
                              capture_output=True, text=True, encoding='utf-8')
        if result.returncode == 0:
            print(f"✅ {description} 成功")
            return True
        else:
            print(f"❌ {description} 失败")
            if result.stderr:
                print(f"错误: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ {description} 异常: {e}")
        return False

def check_environment():
    """检查打包环境"""
    print_step("1", "检查打包环境")
    
    # 检查Python环境
    python_version = sys.version_info
    print(f"Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    # 检查PyInstaller
    try:
        result = subprocess.run(['pyinstaller', '--version'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ PyInstaller版本: {result.stdout.strip()}")
        else:
            print("❌ PyInstaller未安装")
            return False
    except FileNotFoundError:
        print("❌ PyInstaller未找到")
        return False
    
    # 检查必要文件
    required_files = [
        'main_new.py',
        'client_gui.py', 
        'tools/service_config_manager.py',
        'wms_service.py',
        'wms_clean.spec',
        'service_config_manager.spec',
        'wms_service.spec',
        'build_for_deployment.py',
        'build_client.py'
    ]
    
    missing_files = []
    for file in required_files:
        if not Path(file).exists():
            missing_files.append(file)
    
    if missing_files:
        print("❌ 缺少必要文件:")
        for file in missing_files:
            print(f"   - {file}")
        return False
    
    print("✅ 环境检查通过")
    return True

def clean_build_directories():
    """清理构建目录"""
    print_step("2", "清理构建目录")
    
    dirs_to_clean = ['build', 'dist']
    for dir_name in dirs_to_clean:
        if Path(dir_name).exists():
            shutil.rmtree(dir_name)
            print(f"✅ 清理目录: {dir_name}")
    
    # 清理旧的spec文件（动态生成的）
    spec_files_to_clean = ['client.spec']
    for spec_file in spec_files_to_clean:
        if Path(spec_file).exists():
            Path(spec_file).unlink()
            print(f"✅ 清理文件: {spec_file}")

def prepare_packaging():
    """准备打包"""
    print_step("3", "准备打包数据")
    
    # 运行打包准备脚本
    if Path('scripts/prepare_for_packaging.py').exists():
        return run_command(
            f'"{sys.executable}" scripts/prepare_for_packaging.py',
            "准备打包数据"
        )
    else:
        print("⚠️ 打包准备脚本不存在，跳过")
        return True

def build_main_application():
    """打包主程序"""
    print_step("4", "打包主程序 (WMS Sample)")
    
    return run_command(
        f'"{sys.executable}" build_for_deployment.py',
        "主程序打包"
    )

def build_client_application():
    """打包客户端程序"""
    print_step("5", "打包客户端程序 (WMS Client)")
    
    return run_command(
        f'"{sys.executable}" build_client.py',
        "客户端程序打包"
    )

def build_service_applications():
    """打包服务配置应用（两个exe）"""
    print_step("6", "打包服务配置应用")
    
    success_count = 0
    
    # 6.1 打包服务配置管理器
    print("\n6.1 打包服务配置管理器...")
    if run_command(
        'pyinstaller --clean service_config_manager.spec',
        "服务配置管理器打包"
    ):
        success_count += 1
    
    # 6.2 打包Windows服务
    print("\n6.2 打包Windows服务...")
    if run_command(
        'pyinstaller --clean wms_service.spec',
        "Windows服务打包"
    ):
        success_count += 1
    
    return success_count == 2

def create_final_package():
    """创建最终发布包"""
    print_step("7", "创建最终发布包")
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    package_name = f"WMS_Complete_Package_{timestamp}"
    package_dir = Path(package_name)
    
    if package_dir.exists():
        shutil.rmtree(package_dir)
    
    package_dir.mkdir()
    
    # 复制所有打包结果
    copy_tasks = []
    
    # 查找主程序包
    main_packages = list(Path('.').glob('WMS_Sample_v2.1.0_Production_*'))
    if main_packages:
        latest_main = max(main_packages, key=lambda p: p.stat().st_mtime)
        copy_tasks.append((latest_main, package_dir / "WMS_Main"))
    
    # 查找客户端包
    client_packages = list(Path('.').glob('WMS_Client_v2.1.0_Production_*'))
    if client_packages:
        latest_client = max(client_packages, key=lambda p: p.stat().st_mtime)
        copy_tasks.append((latest_client, package_dir / "WMS_Client"))
    
    # 复制服务配置应用
    if Path('dist/service_config_manager').exists():
        copy_tasks.append((Path('dist/service_config_manager'), package_dir / "Service_Manager"))
    
    if Path('dist/wms_service').exists():
        copy_tasks.append((Path('dist/wms_service'), package_dir / "WMS_Service"))
    
    # 执行复制
    for src, dst in copy_tasks:
        if src.exists():
            if src.is_dir():
                shutil.copytree(src, dst)
            else:
                shutil.copy2(src, dst)
            print(f"✅ 复制: {src.name} -> {dst.name}")
    
    # 创建总体说明文档
    create_package_readme(package_dir)
    
    # 创建启动脚本
    create_package_scripts(package_dir)
    
    print(f"✅ 最终发布包创建完成: {package_name}")
    return package_name

def create_package_readme(package_dir):
    """创建包说明文档"""
    readme_content = """# WMS Sample 完整部署包

## 📦 包含内容

### 1. WMS_Main - 主程序
- WMS_Sample.exe - 主要的WMS料位管理系统
- 包含完整的Web界面和API服务

### 2. WMS_Client - 客户端程序  
- WMS_Client.exe - 图形界面客户端
- 连接到WMS主程序进行操作

### 3. Service_Manager - 服务配置管理器
- service_config_manager.exe - 图形界面配置工具
- 用于管理Windows服务和系统配置

### 4. WMS_Service - Windows服务
- wms_service.exe - Windows服务程序
- 将WMS包装为系统服务运行

## 🚀 部署说明

### 快速启动
1. 进入 WMS_Main 目录
2. 运行 启动WMS系统.bat
3. 浏览器访问 http://localhost:58501

### 服务部署
1. 进入 Service_Manager 目录
2. 以管理员身份运行 service_config_manager.exe
3. 安装并启动Windows服务

### 客户端使用
1. 确保WMS主程序已启动
2. 进入 WMS_Client 目录
3. 运行 WMS_Client.exe

## 📞 技术支持

如有问题，请查看各目录下的详细文档。
"""
    
    with open(package_dir / "README.md", 'w', encoding='utf-8') as f:
        f.write(readme_content)

def create_package_scripts(package_dir):
    """创建包启动脚本"""
    # 一键启动脚本
    start_script = package_dir / "一键启动WMS.bat"
    with open(start_script, 'w', encoding='gbk') as f:
        f.write("""@echo off
title WMS Sample 一键启动
color 0A
echo.
echo ========================================
echo    WMS Sample 一键启动
echo ========================================
echo.
echo 正在启动WMS主程序...
cd /d "%~dp0\\WMS_Main"
start "" "启动WMS系统.bat"
echo.
echo WMS主程序已启动
echo 请在浏览器中访问: http://localhost:58501
echo.
pause
""")

def verify_packages():
    """验证打包结果"""
    print_step("8", "验证打包结果")
    
    verification_results = []
    
    # 检查主程序包
    main_packages = list(Path('.').glob('WMS_Sample_v2.1.0_Production_*'))
    if main_packages:
        latest_main = max(main_packages, key=lambda p: p.stat().st_mtime)
        exe_file = latest_main / "WMS_Sample.exe"
        if exe_file.exists():
            verification_results.append(("主程序", "✅ 通过"))
        else:
            verification_results.append(("主程序", "❌ exe文件不存在"))
    else:
        verification_results.append(("主程序", "❌ 包目录不存在"))
    
    # 检查客户端包
    client_packages = list(Path('.').glob('WMS_Client_v2.1.0_Production_*'))
    if client_packages:
        latest_client = max(client_packages, key=lambda p: p.stat().st_mtime)
        exe_file = latest_client / "WMS_Client" / "WMS_Client.exe"
        if exe_file.exists():
            verification_results.append(("客户端程序", "✅ 通过"))
        else:
            verification_results.append(("客户端程序", "❌ exe文件不存在"))
    else:
        verification_results.append(("客户端程序", "❌ 包目录不存在"))
    
    # 检查服务配置管理器
    service_manager_exe = Path('dist/service_config_manager/service_config_manager.exe')
    if service_manager_exe.exists():
        verification_results.append(("服务配置管理器", "✅ 通过"))
    else:
        verification_results.append(("服务配置管理器", "❌ exe文件不存在"))
    
    # 检查Windows服务
    wms_service_exe = Path('dist/wms_service/wms_service.exe')
    if wms_service_exe.exists():
        verification_results.append(("Windows服务", "✅ 通过"))
    else:
        verification_results.append(("Windows服务", "❌ exe文件不存在"))
    
    # 输出验证结果
    print("\n验证结果:")
    for name, result in verification_results:
        print(f"  {name:<15}: {result}")
    
    success_count = sum(1 for _, result in verification_results if "✅" in result)
    total_count = len(verification_results)
    
    print(f"\n总体结果: {success_count}/{total_count} 个应用打包成功")
    return success_count == total_count

def main():
    """主函数"""
    print_header("WMS系统完整重新打包")
    print("包含三类应用:")
    print("1. 主程序 (WMS Sample)")
    print("2. 客户端程序 (WMS Client)")  
    print("3. 服务配置应用 (配置管理器 + Windows服务)")
    
    start_time = datetime.now()
    
    # 执行打包流程
    steps = [
        check_environment,
        clean_build_directories,
        prepare_packaging,
        build_main_application,
        build_client_application,
        build_service_applications,
        create_final_package,
        verify_packages
    ]
    
    for i, step_func in enumerate(steps, 1):
        try:
            if not step_func():
                print(f"\n❌ 步骤 {i} 失败，打包中止")
                return False
        except Exception as e:
            print(f"\n❌ 步骤 {i} 异常: {e}")
            return False
    
    end_time = datetime.now()
    duration = end_time - start_time
    
    print_header("打包完成")
    print(f"✅ 所有应用打包成功!")
    print(f"⏱️ 总耗时: {duration}")
    print(f"📦 最终包位置: 查看当前目录下的 WMS_Complete_Package_* 文件夹")
    
    return True

if __name__ == "__main__":
    success = main()
    input("\n按回车键退出...")
    sys.exit(0 if success else 1) 